<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="50%"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm"/>
  </BasicDrawer>
</template>
<script lang="ts">
  import {defineComponent, ref, computed, unref} from 'vue';
  import {BasicForm, useForm} from '/@/components/Form/index';
  import {BasicDrawer, useDrawerInner} from '/@/components/Drawer';
  import {formSchema} from './apps.data';
  import {saveOrUpdate} from './apps.api';

  export default defineComponent({
    name: 'MchAppDrawer',
    components: {BasicDrawer, BasicForm},
    emits: ['success', 'register'],
    setup(_, {emit}) {
      const isUpdate = ref(true);

      const [registerForm, {resetFields, setFieldsValue, validate}] = useForm({
        labelWidth: 100,
        schemas: formSchema,
        showActionButtonGroup: false,
        baseColProps: {lg: 12, md: 24},
      });

      const [registerDrawer, {setDrawerProps, closeDrawer}] = useDrawerInner(async (data) => {
        resetFields();
        setDrawerProps({confirmLoading: false});
        isUpdate.value = !!data?.isUpdate;

        if (unref(isUpdate)) {
          setFieldsValue({
            ...data.record,
          });
        }
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增商户应用' : '编辑商户应用'));

      async function handleSubmit() {
        try {
          const values = await validate();
          setDrawerProps({confirmLoading: true});
          await saveOrUpdate(values, isUpdate.value);
          closeDrawer();
          emit('success');
        } finally {
          setDrawerProps({confirmLoading: false});
        }
      }

      return {
        registerDrawer,
        registerForm,
        handleSubmit,
        getTitle,
      };
    },
  });
</script>
